package com.quan.system.common.amqp.consumer;

import java.util.Map;

import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import com.quan.common.constant.CommonConstant;
import com.quan.system.entity.SystemLog;
import com.quan.system.service.SystemLogService;
import com.rabbitmq.client.Channel;

/**
 * 消费端-消息队列监听
 * @author yhaoquan
 *
 */
//@Slf4j
@Component
public class ConsumerMessageLogger {
	
	//高德地图KEY 2b7d6cf58cefb5511c218cf37d776ba0
	
	//@Autowired
	//private SystemValueProperties systemValueProperties;

	@Autowired
	private SystemLogService logService;
	
	// 配置监听器
	@RabbitListener(
			bindings = @QueueBinding(
					//队列(队列的名称,是否持久化)
					value = @Queue(value = CommonConstant.QUEUE_TOPIC_LOGGER, durable = "true"),
					//交换机(交换机的名称,是否持久化,交换机类型)
					exchange = @Exchange(name = CommonConstant.EXCHANGE_TOPIC_LOGGER, durable = "true", type = "topic"),
					//队列Routiny Key
					key = CommonConstant.QUEUE_TOPIC_LOGGER
			)
	)

	@RabbitHandler
	public void process(@Payload SystemLog entity, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		//log.info("==>【RabbitMQ 消息消费端】记录操作日志，队列的名称:{}, 交换机:{}, 路由Key:{}, 消息类型:{}", CommonConstant.QUEUE_TOPIC_LOGGER, CommonConstant.EXCHANGE_TOPIC_LOGGER, CommonConstant.QUEUE_TOPIC_LOGGER, CommonConstant.RABBITMQ_TYPE_TOPIC);
		
		if(null != entity.getIp() && !entity.getIp().equals("127.0.0.1")) {
//			LocationBean ipLocation = IpHelper.getIpLocation(this.systemValueProperties.getAmap().getKey(), entity.getIp());
//			if(null != ipLocation) {
//				entity.setIpLocation(ipLocation.getCity());
//			} else {
//				entity.setIpLocation(entity.getIp());
//			}
		} else {
			if(entity.getIp().equals("127.0.0.1")) {
				entity.setIpLocation("本地");
			} else {
				entity.setIpLocation("未知");
			}
		}
		
		this.logService.save(entity);
		
		//log.info("==>操作日志消息：{}", JSON.toJSONString(entity));
		
		//ACK签收（delivery_tag，是否批量签收）
		channel.basicAck((Long) headers.get(AmqpHeaders.DELIVERY_TAG), false);
		
	}
	

}
